/*
 * Copyright (c) 2009, David A. Freels Sr.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 * the following conditions are met:
 *
 *     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *     * Neither the name of the <ORGANIZATION> nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

package net.whippetcode.plugins.intellij.hudson.parser;

import net.whippetcode.plugins.intellij.hudson.domain.job.Build;
import net.whippetcode.plugins.intellij.hudson.domain.job.BuildType;
import net.whippetcode.plugins.intellij.hudson.domain.job.ChangeSetItem;
import net.whippetcode.plugins.intellij.hudson.domain.job.ChangeSetItemPath;
import net.whippetcode.plugins.intellij.hudson.domain.job.EditType;
import net.whippetcode.plugins.intellij.hudson.domain.job.Job;
import net.whippetcode.plugins.intellij.hudson.domain.job.Status;
import net.whippetcode.plugins.intellij.hudson.util.LogUtil;
import net.whippetcode.plugins.intellij.hudson.util.XMLUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPathExpressionException;
import java.io.IOException;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;

/**
 * This class handles parsing the Job related Hudson api.
 *
 * @author David A. Freels Sr.
 */
public class JobHandler
{
	private static final DateFormat DATE_FORMAT = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

	private static final String DISABLED = "disabled";
	private static final String JOB = "job";
	private static final String NAME = "name";
	private static final String COLOR = "color";
	private static final String INQUEUE = "inQueue";
	private static final String NUMBER = "number";
	private static final String TIMESTAMP = "timestamp";
	private static final String CHANGESET_ITEMS = "changeSet/item";
	private static final String PATHS = "path";
	private static final String EDIT_TYPE = "editType";
	private static final String FILE = "file";
	private static final String REVISION = "revision";
	private static final String MESSAGE = "msg";
	private static final String USER = "user";
	private static final String LAST_SUCCESSFUL_BUILD = "lastSuccessfulBuild";
	private static final String LAST_FAILED_BUILD = "lastFailedBuild";
	private static final String LAST_STABLE_BUILD = "lastStableBuild";

	private List<Job> jobList = new ArrayList<Job>();
	private Status status = Status.DISABLED;
	private StringBuilder statusMessage;
	private String serverAddress;

	public JobHandler(URL url, String serverAddress) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException
	{
		this.serverAddress = serverAddress;
		statusMessage = new StringBuilder("<html><body><table border=0>");

		Document doc = XMLUtil.createDocument(url);
		Element element = doc.getDocumentElement();

		NodeList jobs = XMLUtil.getElements(JOB, element);
		parseJobs(jobs);

		statusMessage.append("</table></body></html>");
	}

	public Status getStatus()
	{
		return status;
	}

	public String getStatusSummary()
	{
		return statusMessage.toString();
	}

	private void parseJobs(NodeList jobs) throws XPathExpressionException
	{
		int size = jobs.getLength();
		Node jobNode;
		Job job;

		for (int i = 0; i < size; i++)
		{
			jobNode = jobs.item(i);
			job = new Job();

			job.setName(XMLUtil.getTextElement(NAME, jobNode));
			parseStatus(XMLUtil.getTextElement(COLOR, jobNode), job);
			job.setQueued("true".equalsIgnoreCase(XMLUtil.getTextElement(INQUEUE, jobNode)));
			job.setServerAddress(this.serverAddress);
			Node node = XMLUtil.getElement(LAST_SUCCESSFUL_BUILD, jobNode);
			if (node != null)
			{
				job.addBuild(parseBuild(node, job, BuildType.SUCCESSFUL));
			}
			node = XMLUtil.getElement(LAST_FAILED_BUILD, jobNode);
			if (node != null)
			{
				job.addBuild(parseBuild(node, job, BuildType.FAILED));
			}
			node = XMLUtil.getElement(LAST_STABLE_BUILD, jobNode);
			if (node != null)
			{
				job.addBuild(parseBuild(node, job, BuildType.STABLE));
			}
			jobList.add(job);
		}

	}

	private void parseStatus(String color, Job job)
	{
		if (color.indexOf("_") != -1)
		{
			job.setRunning(true);
			color = color.substring(0, color.indexOf("_"));
		}

		if ("grey".equalsIgnoreCase(color) || "aborted".equalsIgnoreCase(color))
		{
			color = DISABLED;
		}

		try
		{
			job.setStatus(Status.valueOf(color.toUpperCase()));
		}
		catch (IllegalArgumentException e)
		{
			LogUtil.log(Level.WARNING, e.getMessage(), e);
		}

		if (status.compareTo(job.getStatus()) > 0)
		{
			status = job.getStatus();
		}

		statusMessage.append("<tr><td>").append(job.getName()).append("</td><td bgcolor=").append(job.getStatus() == Status.DISABLED ? "gray" : job.getStatus().name().toLowerCase()).append("></td></tr>");
	}

	private Build parseBuild(Node buildNode, Job job, BuildType type) throws XPathExpressionException
	{
		String date = "";
		if (XMLUtil.hasContent(TIMESTAMP, buildNode))
		{
			String timestamp = XMLUtil.getTextElement(TIMESTAMP, buildNode);

			Date d = new Date();
			d.setTime(Long.parseLong(timestamp));
			date = DATE_FORMAT.format(d);
		}

		Build build = new Build(); //type, revision, date, job.getName(), job.getServerAddress());

		//Parse the Change Set
		parseChangeSet(buildNode, build);

		return build;
	}

	private void parseChangeSet(Node buildNode, Build build) throws XPathExpressionException
	{
		NodeList items = XMLUtil.getElements(CHANGESET_ITEMS, buildNode);
		int itemCount = items.getLength();
		Node item;
		for (int i = 0; i < itemCount; i++)
		{
			item = items.item(i);
			ChangeSetItem csItem = new ChangeSetItem();
			csItem.setMessage(XMLUtil.getTextElement(MESSAGE, item));
			csItem.setRevision(XMLUtil.getTextElement(REVISION, item));
			csItem.setUser(XMLUtil.getTextElement(USER, item));

			parsePath(item, csItem);

			build.addItem(csItem);
		}
	}

	private void parsePath(Node csNode, ChangeSetItem csItem) throws XPathExpressionException
	{
		NodeList paths = XMLUtil.getElements(PATHS, csNode);
		int pathCount = paths.getLength();
		Node path;
		for (int i = 0; i < pathCount; i++)
		{
			path = paths.item(i);
			ChangeSetItemPath csPath = new ChangeSetItemPath();
			csPath.setFilePath(XMLUtil.getTextElement(FILE, path));
			if (XMLUtil.hasContent(EDIT_TYPE, path))
			{
				String editType = XMLUtil.getTextElement(EDIT_TYPE, path);
				csPath.setEditType(EditType.valueOf(editType.toUpperCase()));
			}
			csItem.addPath(csPath);
		}
	}

	public List<Job> getJobList()
	{
		return jobList;
	}
}
